var __assign = (this && this.__assign) || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i]
      for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p)) {
          t[p] = s[p]
        }
      }
    }
    return t
  }
  return __assign.apply(this, arguments)
}

export default {
  list2Tree(list, config) {
    var id = config && config.id || 'id'
    var pid = config && config.pid || 'pid'
    var children = config && config.children || 'children'
    var idMap = {}
    var jsonTree = []
    list.forEach(function(v) { idMap[v[id]] = v })
    list.forEach(function(v) {
      var parent = idMap[v[pid]]
      if (parent) {
        !parent[children] && (parent[children] = [])
        parent[children].push(v)
      } else {
        jsonTree.push(v)
      }
    })
    return jsonTree
  },
  tree2List(tree, config) {
    var id = config && config.id || 'id'
    var pid = config && config.pid || 'pid'
    var children = config && config.children || 'children'
    function flatTree(tree) {
      var queue = [tree]
      var result = []
      var _loop_1 = function() {
        var _a
        var currentNode = queue.shift()
        if (currentNode.hasOwnProperty(id)) {
          if (!currentNode.hasOwnProperty(pid)) {
            currentNode = __assign({}, currentNode, (_a = {}, _a[pid] = null, _a))
          }
          if (currentNode[children]) {
            currentNode[children].forEach(function(v) {
              var _a
              queue.push(__assign({}, v, (_a = {}, _a[pid] = currentNode[id], _a)))
              return queue
            })
          }
          result.push(currentNode)
          delete currentNode[children]
        } else {
          throw new Error('you need to specify the [id] of the json tree')
        }
      }
      while (queue.length) {
        _loop_1()
      }
      return result
    }
    if (Array.isArray(tree)) {
      return tree.map(function(v) { return flatTree(v) }).reduce(function(pre, cur) { return pre.concat(cur) })
    } else {
      return flatTree(tree)
    }
  }
}
